/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.ouwen.smartpay.service.chain.slotchain;

import com.google.common.collect.Lists;
import com.ouwen.smartpay.service.chain.context.Context;

import java.util.ArrayList;

/***
 *@author <a href="http://youngitman.tech">青年IT男</a>
 *@version v1.0.0
 *@className AbstractLinkedProcessorSlot
 *@description 抽象实现，默认第一个Slot和最后一个Slot相连接
 *@JunitTest: {@link  }
 *@date 11:10 2020-04-22
 *
 **/
public abstract class AbstractLinkedProcessorSlot<T> implements ProcessorSlot<T> {

    private AbstractLinkedProcessorSlot<?> next = null;

    private AbstractLinkedProcessorSlot<?> pre = null;

    @Override
    public void fireEntry(Context context, Object obj, Object... args)
            throws Throwable {
        if (next != null) {
            next.transformEntry(context, obj, args);
        } else {

            if (args.length > 0) {

                ArrayList<Object> objects = Lists.newArrayList();

                for (int i = 0; i < args.length; i++) {

                    objects.add(args[i]);
                }

                ArrayList<Object> objectsAll = Lists.newArrayList(obj);

                objectsAll.addAll(objects);

                exit(context, objectsAll.toArray(new Object[args.length+1]));
            } else {

                exit(context, obj, args);
            }
        }
    }

    @SuppressWarnings("unchecked")
    void transformEntry(Context context, Object o, Object... args)
            throws Throwable {
        T t = (T) o;
        entry(context, t, args);
    }

    @Override
    public void fireExit(Context context, Object... args) {
        if (pre != null) {
            pre.exit(context, args);
        }
    }

    public AbstractLinkedProcessorSlot<?> getNext() {
        return next;
    }

    public void setNext(AbstractLinkedProcessorSlot<?> next) {
        this.next = next;
    }

    public void setPre(AbstractLinkedProcessorSlot<?> pre) {
        this.pre = pre;
    }

}
